package com.zshy.base.sms.service.impl;

import cn.hutool.http.HttpUtil;
import com.zshy.base.sms.contract.constant.SmsConstant;
import com.zshy.base.sms.contract.enums.SmsErrorEnum;
import com.zshy.base.sms.contract.enums.SmsTypeEnum;
import com.zshy.base.sms.contract.exception.SmsException;
import com.zshy.base.sms.properties.SmsProperties;
import com.zshy.base.sms.service.AbstractSmsTypeOperator;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 博士通发送短信接口
 *
 * @author zhouhengzhe
 * @version 1.0
 */
public class BoshitongSmsTypeOperator extends AbstractSmsTypeOperator {

    private SmsProperties.BoshitongSmsProperties boshitongSmsProperties;

    @Override
    public String getName() {
        return SmsTypeEnum.BOSHITONG.getCode();
    }

    @Override
    public void init(SmsProperties smsProperties) {
        if (Objects.isNull(smsProperties)
                || Objects.isNull(smsProperties.getBoshitong())
                || Objects.isNull(smsProperties.getBoshitong().getUid())
                || Objects.isNull(smsProperties.getBoshitong().getPwd())
                || Objects.isNull(smsProperties.getBoshitong().getSrcphone())) {
            throw new SmsException(SmsErrorEnum.BOSHITONG_CONFIG_IS_NULL);
        }
        boshitongSmsProperties = smsProperties.getBoshitong();
    }

    /**
     * 发送单条信息
     *
     * @param phoneNumber    手机号码
     * @param template       模板
     * @param templateParams 模板参数
     * @param signName       签名
     * @return 发送是否成功
     */
    @Override
    public Boolean sendSingle(String phoneNumber, String template, Map<String, String> templateParams, String signName) {
        super.checkParam(phoneNumber, template, templateParams, signName);
        Map<String, Object> params = createBaseParams();
        params.put("mobile", phoneNumber);
        try {
            String content = template;
            //替换成如下
            for (Map.Entry<String, String> entry : templateParams.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                content = content.replace(key, value);
            }
            params.put("msg", URLEncoder.encode(signName + content, String.valueOf(StandardCharsets.UTF_8)));
        } catch (UnsupportedEncodingException e) {
            throw new SmsException(e);
        }
        String response = HttpUtil.post(SmsConstant.BOSHITONG_URL, params);
        String[] result = response.split(",");
        return "0".equals(result[0]);
    }

    public Map<String, Object> createBaseParams() {
        Map<String, Object> param = new HashMap<>();
        param.put("uid", boshitongSmsProperties.getUid());
        param.put("pwd", boshitongSmsProperties.getPwd());
        param.put("srcphone", boshitongSmsProperties.getSrcphone());
        return param;
    }
}
